package com.hello.facerecognition;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import butterknife.ButterKnife;
import butterknife.InjectView;
import com.google.gson.Gson;
import com.hello.facerecognition.Application.BaseApplication;
import com.hello.facerecognition.com.hello.utils.StringUtils;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Request;
import okhttp3.Response;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class ShowActivity extends AppCompatActivity implements View.OnClickListener {
    public  static Integer Request_Code = 1000;
    @InjectView(R.id.button7)
    Button photo;

    @InjectView(R.id.imageView)
    ImageView show_photo;

    @InjectView(R.id.textView)
    TextView textView;

    @InjectView(R.id.next)
    Button next_back;

    @InjectView(R.id.recognition)
    Button recognition;

    String file_path = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_show);
        ButterKnife.inject(this);
        photo.setOnClickListener(this);
        next_back.setOnClickListener(this);
        recognition.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.button7:{
                if (ActivityCompat.checkSelfPermission(BaseApplication.context, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED) {
                    //未获得，向用户请求
                    Log.d("No permission: ", "开始请求权限");
                    ActivityCompat.requestPermissions(this, new String[]
                            {Manifest.permission.WRITE_EXTERNAL_STORAGE}, 200);
                } else {
                    Intent intent = new Intent(this, Photo.class);
                    startActivityForResult(intent,Request_Code);
                }
                break;
            }
            case R.id.next:{
                this.finish();
                break;
            }
            case R.id.recognition:{
                if(StringUtils.isNullOrEmpty(file_path.trim())){
                    showFailRegister(R.drawable.sorry,"抱歉","还未选择照片！");
                }else{
                    Recognition recognition1 = new Recognition();
                    recognition1.execute(file_path);
                }
                break;
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
        if(data != null) {
            if (requestCode == Request_Code) {
                String filePath = data.getStringExtra("file_path");
                String absolutePath = data.getStringExtra("uri");
                System.out.println(absolutePath);
                if (!StringUtils.isNullOrEmpty(absolutePath)) {
                    try {
                        show_photo.setImageURI(Uri.fromFile(new File(absolutePath)));
                    } catch (Exception e) {
                        Log.e("error", e.getMessage());
                    }
                }
                Log.d("Path:", filePath);
                file_path = filePath;
            }
        }
    }

    private void showMultiBtnDialog(){
        @SuppressWarnings("deprecation")
        AlertDialog.Builder builder = new AlertDialog.Builder(this,R.style.AppCompat);
        AlertDialog.Builder normalDialog =
                builder;
        normalDialog.setIcon(R.drawable.sorry);
        normalDialog.setTitle("凉凉").setMessage("图片上传失败，请重试");
        normalDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // ...To-
                    }
                });
        // 创建实例并显示
        normalDialog.create().show();
    }

    private void showFailRegister(Integer iconId,String title,String message){
        @SuppressWarnings("deprecation")
        AlertDialog.Builder builder = new AlertDialog.Builder(this,R.style.AppCompat);
        AlertDialog.Builder normalDialog =
                builder;
        normalDialog.setIcon(iconId);
        normalDialog.setTitle(title).setMessage(message);
        normalDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // ...To-
                    }
                });
        // 创建实例并显示
        normalDialog.create().show();
    }

    public void FaceRecognition(){
        String url = String.format("http://47.92.246.214:9988/identify.php?img=%s",file_path);
        Request request = new Request.Builder()
                .url(url)
                .build();
        BaseApplication.okHttpClient.newCall(request).enqueue(new Callback(){
            @Override
            public void onFailure(Call call, IOException e) {
                ShowActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        textView.setText("识别失败： 服务器错误");
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String json = response.body().string();
                Log.i("json: ",json);
                if(!StringUtils.isNullOrEmpty(json)){
                    final Map<String,String> map = new Gson().fromJson(json,Map.class);
                    System.out.println(map);
                    if(map != null){
                        if(0 == Double.parseDouble(String.valueOf(map.get("code")))){
                            ShowActivity.this.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    textView.setText(String.format("识别成功： %s",map == null ? "" : map.get("user_name")));
                                }
                            });
                        }else{
                            ShowActivity.this.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    textView.setText("识别失败： "+map == null ? "服务器错误" : map.get("msg"));
                                }
                            });
                        }
                    }else{
                        ShowActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                textView.setText("识别失败： 服务器错误");
                            }
                        });
                    }
                }else{
                    ShowActivity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            textView.setText("识别失败： 服务器错误");
                        }
                    });                }
            }
        });
    }

    class Recognition extends AsyncTask {
        public Recognition(){
            super();
        }

        @Override
        protected Object doInBackground(Object[] objects) {
            FaceRecognition();
            return null;
        }

    }
}
